import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  //项目路径重定向
  {
    path: "/",
    redirect: "/login",
  },
  //配置登录路由
  {
    path: "/login",
    name: "login",
    component: () => import("../components/login.vue"),
    meta: { title: "欢迎登录" },
  },
  //配置主页路由
  {
    path: "/home",
    name: "home",
    redirect: "/welcome",
    component: () => import("../components/Home.vue"),
    children: [
      //配置欢迎页路由
      {
        path: "/welcome",
        name: "welcome",
        component: () => import("../components/Welcome.vue"),
        meta: { title: "首页" },
      },
      //配置用户列表页路由
      {
        path: "/users",
        name: "users",
        component: () => import("../components/user/Users.vue"),
        meta: { title: "用户列表" },
      },
      //配置用户权限列表页路由
      {
        path: "/rights",
        name: "rights",
        component: () => import("../components/power/Rights.vue"),
        meta: { title: "用户权限列表" },
      },
      //配置角色列表页路由
      {
        path: "/roles",
        name: "roles",
        component: () => import("../components/power/Roles.vue"),
        meta: { title: "角色列表" },
      },
      //配置商品分类页路由
      {
        path: "/categories",
        name: "categories",
        component: () => import("../components/goods/Cate.vue"),
        meta: { title: "商品分类" },
      },
      //配置商品参数页路由
      {
        path: "/params",
        name: "params",
        component: () => import("../components/goods/Params.vue"),
        meta: { title: "商品参数" },
      },
      //配置商品列表页路由
      {
        path: "/goods",
        name: "goods",
        component: () => import("../components/goods/List.vue"),
        meta: { title: "商品列表" },
      },
      //配置添加商品页路由
      {
        path: "/goods/add",
        name: "/goods/add",
        component: () => import("../components/goods/Add.vue"),
        meta: { title: "添加商品" },
      },
      //配置商品订单页路由
      {
        path: "/orders",
        name: "/orders",
        component: () => import("../components/order/Order.vue"),
        meta: { title: "商品订单" },
      },
      //配置商品数据报表页路由
      {
        path: "/reports",
        name: "/reports",
        component: () => import("../components/report/Report.vue"),
        meta: { title: "商品数据报表" },
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

//挂载路由导航守卫(路由拦截)
router.beforeEach((to, from, next) => {
  //to 将要访问的路径
  //from 代表从哪一个路径跳转而来
  //next()函数 代表放行
  //获取标题名称
  document.title = to.meta.title;
  //console.log(to);
  if (to.path === "/login") {
    next();
  } else {
    //获取token
    const tokenStr = window.sessionStorage.getItem("token");
    if (!tokenStr) {
      //如果未拿到token强制退出返回登录页
      return next("/login");
    } else {
      next();
    }
  }
});

export default router;
